<%@ page language="java" contentType="text/html; charset=UTF-8" import="java.util.*,
com.brother.model.*,com.brother.service.*,com.brother.realtime.*,com.brother.realtime.config.*"   pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@ include file="../international.jsp" %> 
<%
String trackerId = request.getParameter("trackerId");
TrackerService tks = new TrackerService();

Tracker tracker = tks.getTrackerByFieldName("trackerId", trackerId);

AlarmService alService = new AlarmService();
Alarm overSpeedAlarm = new Alarm();
overSpeedAlarm.setTrackerId(trackerId);
overSpeedAlarm.setAlarmType(AlarmType.Over_Speed_Alarm.toString());
List<Alarm> alarms = alService.findAlarms(overSpeedAlarm);
overSpeedAlarm = alarms.size() > 0 ? alarms.get(0):null;


Alarm numberAAlarm = new Alarm();
numberAAlarm.setTrackerId(trackerId);
numberAAlarm.setAlarmType(AlarmType.Number_A.toString());
alarms = alService.findAlarms(numberAAlarm);
numberAAlarm = alarms.size() > 0 ? alarms.get(0):null;

Alarm numberBAlarm = new Alarm();
numberBAlarm.setTrackerId(trackerId);
numberBAlarm.setAlarmType(AlarmType.Number_B.toString());
alarms = alService.findAlarms(numberBAlarm);
numberBAlarm = alarms.size() > 0 ? alarms.get(0):null;

Alarm numberCAlarm = new Alarm();
numberCAlarm.setTrackerId(trackerId);
numberCAlarm.setAlarmType(AlarmType.Number_C.toString());
alarms = alService.findAlarms(numberCAlarm);
numberCAlarm = alarms.size() > 0 ? alarms.get(0):null;

Alarm numberDAlarm = new Alarm();
numberDAlarm.setTrackerId(trackerId);
numberDAlarm.setAlarmType(AlarmType.Number_D.toString());
alarms = alService.findAlarms(numberDAlarm);
numberDAlarm = alarms.size() > 0 ? alarms.get(0):null;


Alarm timezoneAlarm = new Alarm();
timezoneAlarm.setTrackerId(trackerId);
timezoneAlarm.setAlarmType(AlarmType.Set_Time_Zone.toString());
alarms = alService.findAlarms(timezoneAlarm);
timezoneAlarm = alarms.size() > 0 ? alarms.get(0):null;

Alarm moveAlarm = new Alarm();
moveAlarm.setTrackerId(trackerId);
moveAlarm.setAlarmType(AlarmType.Movement_Alert.toString());
alarms = alService.findAlarms(moveAlarm);
moveAlarm = alarms.size() > 0 ? alarms.get(0):null;

Alarm engineAlarm = new Alarm();
engineAlarm.setTrackerId(trackerId);
engineAlarm.setAlarmType(AlarmType.Engine.toString());
alarms = alService.findAlarms(engineAlarm);
engineAlarm = alarms.size() > 0 ? alarms.get(0):null;


Alarm powerLostAlarm = new Alarm();
powerLostAlarm.setTrackerId(trackerId);
powerLostAlarm.setAlarmType(AlarmType.External_Power_Lost.toString());
alarms = alService.findAlarms(powerLostAlarm);
powerLostAlarm = alarms.size() > 0 ? alarms.get(0):null;

%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title><fmt:message key="tracker.parameters.set"/></title>
<link rel="stylesheet" type="text/css" media="all" href="../style.css"/>
<link rel="stylesheet" type="text/css" href="../css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="../css/examples.css" />
    <script type="text/javascript" src="../js/ext-base.js"></script>
    <script type="text/javascript" src="../js/ext-all.js"></script>
<script type="text/javascript" src="../js/extexample.js"></script>
<script type="text/javascript" src="../js/TableGrid.js"></script>
<script type="text/javascript" src="../js/common.js"></script>

<script type="text/javascript">

var ime = '<%=tracker.getUserTrackerId()%>';
var waitingMsg = '<fmt:message key="waiting.msg"/>';
var waitingProgressText = '<fmt:message key="waiting.loading"/>';

function setSpeedAlarm(type){
	var speed = Ext.get("speed").getValue();
	setInfo();
	Ext.Ajax.request({
	    form: 'control',
	    params: 'action=speed&data='+speed+'&work='+type,
	    success:function(){
			querySetStatus('speed');
	    }
	});
}

var trackerId = '<%=trackerId%>';
var setupmsg = '<fmt:message key="parameters.setup.msg"/>';
var setupProgresstext = '<fmt:message key="parameters.setup.progress"/>';
function setParameter(work, action,data){

	setInfo();
	
	Ext.Ajax.request({
		method:'POST',
		url: './setControl.jsp',
	    params: {action:action,data:data,work:work, trackerId:trackerId},
	    success:function(){
			if(action == 'reqStatus')
				queryAllStatus();
			else
			querySetStatus('speed');
	    }
	});
	
}

function setInfo(){
    Ext.MessageBox.show({
        msg: setupmsg,
        progressText: setupProgresstext,
        width:300,
        //wait:true,
        //waitConfig: {interval:200},
        progress:true,
        closable:false
        //icon:'ext-mb-download'
    });
}

function setReportInterval(type){
	var interval = Ext.get("interval").getValue();
	setInfo();
	Ext.Ajax.request({
	    form: 'control',
	    params: 'action=reportInterval&data='+interval+'&work='+type,
	    success:function(){
			querySetStatus('reportInterval');
	    }
	});
}

function engine(type){
	setInfo();
	Ext.Ajax.request({
	    form: 'control',
	    params: 'action=engine&data='+type,
	    success:function(){
			querySetStatus('engine');
	    }
	});
}

var setSuccess = "<fmt:message key="parameters.set.success"/>";
var setFailed = "<fmt:message key="parameters.set.failed"/>";

var failedCount = 15;

function querySetStatus(action){
	var count = 0;

	function fun(){
		count +=1;

		Ext.Ajax.request({
			url:'queryStatus.jsp',
		    form: 'control',
		    params: 'action='+action,
		    success:function(res){
				var text = res.responseText;
				if(text.indexOf("1") > -1 || text.indexOf('true') > -1){
					Ext.MessageBox.hide();
					Ext.example.msg('<div class="right"></div>', '<div><br/>'+setSuccess+'<div>');
					
					count = failedCount;
					return;
				}else if(count == failedCount){
					Ext.MessageBox.hide();
					//alert(setFailed);
					Ext.MessageBox.show({
        	            title: '',
        	            msg: setFailed,
        	            buttons: Ext.MessageBox.OK,
        	            icon: Ext.MessageBox.ERROR
        	        });
				}
				if(count < failedCount){
					window.setTimeout(fun, 1000);
					var percent = count / failedCount;
					Ext.MessageBox.updateProgress(percent, Math.round(100*percent)+'%');
				}
		    }
		});
	}
	fun();
}


function queryAllStatus(){
	var count = 0;
	
	function fun2(){
		count +=1;

		Ext.Ajax.request({
			url:'queryStatus.jsp',
		    form: 'control',
		    params: 'action=reqStatus',
		    success:function(res){
				var text = res.responseText;
				
				if(text.length > 2){
					var datas = text.split(",");
					Ext.MessageBox.hide();
					if(datas.length >= 9){
						Ext.example.msg('<div class="right"></div>', '<div><br/>'+setSuccess+'<div>');
						count = failedCount;
						
						document.getElementById("numberaText").innerHTML = datas[0];
						document.getElementById("numberbText").innerHTML = datas[1];
						document.getElementById("numbercText").innerHTML = datas[2];
						document.getElementById("numberdText").innerHTML = datas[3];
						document.getElementById("intervalText").innerHTML = datas[4];
						document.getElementById("speedText").innerHTML = datas[5];
						document.getElementById("timezoneText").innerHTML = datas[6];
						document.getElementById("moveAlertText").innerHTML = datas[7];
						document.getElementById("coordinateText").innerHTML = datas[8];
						document.getElementById("listenInText").innerHTML = datas[9];
							
					}else{ //alert(setFailed);
						Ext.MessageBox.show({
	        	            title: '',
	        	            msg: setFailed,
	        	            buttons: Ext.MessageBox.OK,
	        	            icon: Ext.MessageBox.ERROR
	        	        });
					}
					
					return;
				}else if(count == failedCount){
			         Ext.MessageBox.hide();
			        // Ext.example.msg('Done', 'Your fake data was saved!');
			        Ext.MessageBox.show({
	        	            title: '',
	        	            msg: setFailed,
	        	            buttons: Ext.MessageBox.OK,
	        	            icon: Ext.MessageBox.ERROR
	        	        });
					//alert(setFailed);
				}
				if(count < failedCount){
					window.setTimeout(fun2, 1000);
					var percent = count / failedCount;
					Ext.MessageBox.updateProgress(percent, Math.round(100*percent)+'%');
				}
		    }
		});
		
		
	}
	
	
	fun2();
}


Ext.onReady(function(){
	//history.length = 0;
	Ext.MessageBox.buttonText.yes = '<fmt:message key="button.yes.text"/>';
	Ext.MessageBox.buttonText.no = '<fmt:message key="button.no.text"/>';
	Ext.MessageBox.buttonText.cancel = '<fmt:message key="button.cancel.text"/>';
	var buttons = Ext.select('input[type="button"]');
	buttons.each(function(item,c, index){
		//item.setStyle('display','none');
	});
    // create the grid
    Ext.get("plain-table").setStyle('display','');
    
    var grid = new Ext.ux.grid.TableGrid("plain-table", {
        stripeRows: true, // stripe alternate rows
        enableHdMenu:false,
        width:688
    });

    grid.render();

function createButton(){
	return;
    var buttons = grid.getEl().select('input[type="button"]');
    if(buttons.getCount() == 0){
		setTimeout(createButton, 500);
		return;
    }
    //console.log(buttons, 1000, grid.getEl().dom);
    buttons.each(function(item,c, index){
		
        var button = new Ext.Button({renderTo:item.parent(),type:'button', 
			text:item.getAttribute('value'),split: true,enableToggle:false});
		button.on('click',function(){
			try{ eval(item.getAttribute('onclick')); }catch(e){}
			});
        item.remove();
    });
}

//createButton();




});

function checkTimeZone(){
//  document.getElementById('timezone').value.length < 3
	var value = document.getElementById('timezone').value;
	if(!value.match(/^[\+-]\d{1}\.{1}\d{1}$/)
			&& !value.match(/^[\+-]\d{2}$/)){
		Ext.MessageBox.show({
            title: '',
            msg: '<fmt:message key="parameters.timezone.format.error"/>',
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.ERROR
        });
        return false;
	}
	return true;
}

function checkMoveAlert(id){
	var value = document.getElementById(id).value;
	if(!value.match(/^\d{2}$/)){
		Ext.MessageBox.show({
            title: '',
            msg: '<fmt:message key="parameters.move.alert.format.error"/>',
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.ERROR
        });
        return false;
	}
	return true;
	
}

</script>

<style type="text/css">

body{
	background-color:#FFFFFF;
}

.x-grid3-cell-inner  {
text-align:left;
white-space:nowrap;
}

.x-btn{
float: left;
padding-left:3px;
}


</style>

</head><body>
<div style="text-align: center">
<form id="control" name="control" method="post" action="./setControl.jsp">
<input name="trackerId" value="<%=tracker.getTrackerid()%>" type="hidden">

<table align="center" border="1" style="display:none;" id="plain-table"  cellpadding="2" cellspacing="1">
  <tbody>
  <thead>
  <tr>
    <th width="160"><fmt:message key="parameters.operation"/>:</th>
    <th width="220"><fmt:message key="parameters.parameter.value"/>:</th>
    <th width="120"><fmt:message key="parameters.state"/>:</th>
    <th width="180"><fmt:message key="parameters.function.switch"/></th>
  </tr>
  </thead>
  
  <tr>
    <td><fmt:message key="parameters.numbera"/></td>
    <td><input name="numbera" type="text" onclick="this.focus()"  id="numbera" value="<%=numberAAlarm == null ? "":numberAAlarm.getData() %>" size="25"/></td>
    <td  ><div id="numberaText">&nbsp;</div></td>
    <td><a href="#noaction" onclick="setParameter('<%=NumberAConfig.ENABLE %>', 'numbera', document.getElementById('numbera').value);"><fmt:message key="parameters.enable"/></a>
      <a href="#noaction" onclick="setParameter('<%=NumberAConfig.DISABLE %>', 'numbera','');"><fmt:message key="parameters.disable"/></a></td>
  </tr>
  <tr>
    <td><fmt:message key="parameters.numberb"/> </td>
    <td><input name="numberb" type="text" onclick="this.focus()"  id="numberb" value="<%=numberBAlarm == null ? "":numberBAlarm.getData() %>" size="25"/></td>
    <td  ><div id="numberbText">&nbsp;</div></td>
    <td><a href="#noaction" onclick="setParameter('<%=NumberBConfig.ENABLE %>', 'numberb', document.getElementById('numberb').value);"><fmt:message key="parameters.enable"/></a>
      <a href="#noaction" onclick="setParameter('<%=NumberBConfig.DISABLE %>', 'numberb','');"><fmt:message key="parameters.disable"/></a></td>
  </tr>
  <tr>
    <td><fmt:message key="parameters.numberc"/></td>
    <td><input name="numberc" type="text" onclick="this.focus()"  id="numberc" value="<%=numberCAlarm == null ? "":numberCAlarm.getData()%>" size="25"/></td>
    <td  ><div id="numbercText">&nbsp;</div></td>
    <td><a href="#noaction" onclick="setParameter('<%=NumberCConfig.ENABLE %>', 'numberc', document.getElementById('numberc').value);"><fmt:message key="parameters.enable"/></a>
      <a href="#noaction" onclick="setParameter('<%=NumberCConfig.DISABLE %>', 'numberc','');"><fmt:message key="parameters.disable"/></a></td>
  </tr>
  
  <tr>
    <td><fmt:message key="parameters.numberd"/></td>
    <td><input name="numberd" type="text" onclick="this.focus()"  id="numberd" value="<%=numberDAlarm == null ? "":numberDAlarm.getData()%>" size="25"/></td>
    <td  ><div id="numberdText">&nbsp;</div></td>
    <td><a href="#noaction" onclick="setParameter('<%=NumberDConfig.ENABLE %>', 'numberd', document.getElementById('numberd').value);"><fmt:message key="parameters.enable"/></a>
      <a href="#noaction" onclick="setParameter('<%=NumberDConfig.DISABLE %>', 'numberd','');"><fmt:message key="parameters.disable"/></a></td>
  </tr>

   <tr>
    <td align="left"><fmt:message key="parameters.set.time.interval"/></td>
    <td align="left">
    <input name="interval" type="text" onclick="this.focus()"  id="interval" value="<%=tracker.getReportInterval() %>" size="15"/>
    (<fmt:message key="control.report.interval.unit"/>)    </td>
    
    <td align="left"><div id="intervalText">&nbsp;</div></td>
    <td align="left"><a href="#noaction" onclick="setReportInterval('enable');"><fmt:message key="parameters.enable"/></a>
    <a href="#noaction" onclick="setReportInterval('disable');"><fmt:message key="parameters.disable"/></a></td>
  </tr>

  <tr>

    <td><fmt:message key="parameters.over.speed.alarm"/></td>
    <td><input name="speed" type="text" onclick="this.focus()"  id="speed" value="<%=overSpeedAlarm == null ? "":overSpeedAlarm.getValue1() %>" size="15"/> KM/H</td>
    
    <td  ><div id="speedText">&nbsp;</div></td>
    <td><a href="#noaction" onclick="setSpeedAlarm('<%=OverSpeedConfig.ENABLE %>');"><fmt:message key="parameters.enable"/></a>
    <a href="#noaction" onclick="setSpeedAlarm('<%=OverSpeedConfig.DISABLE %>');"><fmt:message key="parameters.disable"/></a>    </td>
  </tr>

  <tr>
    <td><fmt:message key="parameters.modify.time.zone"/></td>
    <td><input name="timezone" type="text" onclick="this.focus()"  id="timezone" value="<%=timezoneAlarm == null ? "":timezoneAlarm.getData() %>" size="15"/>&nbsp;(-11 to +11)</td>
    <td  ><div id="timezoneText">&nbsp;</div></td>
    <td><a href="#noaction" onclick="if(!checkTimeZone()){  return; }; setParameter('<%=TimeZoneConfig.ENABLE %>', 'timezone',document.getElementById('timezone').value);"><fmt:message key="parameters.confirm"/></a>
    <a style="display:none" href="#noaction" onclick="if(!checkTimeZone()){ return; };setParameter('<%=TimeZoneConfig.DISABLE %>', 'timezone','');"><fmt:message key="parameters.disable"/></a>
      </td>
  </tr>
  
  <tr>
    <td><fmt:message key="parameters.movement.alert"/> </td>
    <td><input name="moveAlert" type="text" onclick="this.focus()"  id="moveAlert" value="<%=moveAlarm == null ? "":moveAlarm.getData() %>" size="15"/>&nbsp;xx(unit: 100m)</td>
    <td  ><div id="moveAlertText">&nbsp;</div></td>
    <td><a href="#noaction" onclick="if(checkMoveAlert('moveAlert')) setParameter('<%=MoveAlertConfig.ENABLE %>'+document.getElementById('moveAlert').value, '<%=ActionType.Movement_Alert %>',document.getElementById('moveAlert').value);"><fmt:message key="parameters.move.enable"/></a>
     <a href="#noaction" onclick="setParameter('<%=MoveAlertConfig.DISABLE %>', '<%=ActionType.Movement_Alert %>',document.getElementById('moveAlert').value);"><fmt:message key="parameters.move.disable"/></a></td>
  </tr>

  <tr>
    <td><fmt:message key="parameters.coordinate.save"/></td>
    <td>&nbsp;</td>
    <td  ><div id="coordinateText">&nbsp;</div></td>
    <td><a href="#noaction" onclick="setParameter('<%=SaveCoordinateConfig.ENABLE %>', 'saveCoordinate','');"><fmt:message key="parameters.enable"/></a>
    <a href="#noaction" onclick="setParameter('<%=SaveCoordinateConfig.DISABLE %>', 'saveCoordinate','');"><fmt:message key="parameters.disable"/></a>
    </td>
  </tr>

  <tr>
    <td><fmt:message key="parameters.listen.in"/> </td>
    <td>&nbsp;</td>
    <td  ><div id="listenInText">&nbsp;</div></td>
    <td><a href="#noaction" onclick="setParameter('<%=ListenInConfig.ENABLE %>', '<%=ActionType.Listen_In %>','<%=Alarm.STATE.Enabled.name() %>');"><fmt:message key="parameters.listen.enable"/></a>
     <a href="#noaction" onclick="setParameter('<%=ListenInConfig.DISABLE %>', '<%=ActionType.Listen_In %>','<%=Alarm.STATE.Disabled.name() %>');"><fmt:message key="parameters.listen.disable"/></a></td>
  </tr>

  <tr>
    <td><fmt:message key="parameters.req.status"/></td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td><a href="#noaction" onclick="setParameter('', 'reqStatus','');"><fmt:message key="parameters.request"/></a></td>
  </tr> 
</tbody>
</table>
</form>

</div>

</body></html>
<%
com.brother.database.DataBase.closeThreadConnection();
%>